import React, { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useAppContext, sendCode } from '../context/AppContext';

const Login: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { login, loginByCode, userState, clearError } = useAppContext();
  const { loading, error } = userState;

  // 切换登录方式：密码登录 / 验证码登录
  const [mode, setMode] = useState<'password' | 'code'>('password');

  // 密码登录状态
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  // 验证码登录状态
  const [verifyType, setVerifyType] = useState<'email' | 'phone'>('phone');
  const [account, setAccount] = useState('');
  const [code, setCode] = useState('');
  const [countdown, setCountdown] = useState(0);
  const [localError, setLocalError] = useState<string | null>(null);

  useEffect(() => {
    if (error) {
      // 将上下文错误展示在页面上
      setLocalError(error);
    }
  }, [error]);

  useEffect(() => {
    let timer: number | undefined;
    if (countdown > 0) {
      timer = window.setInterval(() => {
        setCountdown(prev => (prev > 0 ? prev - 1 : 0));
      }, 1000);
    }
    return () => {
      if (timer) window.clearInterval(timer);
    };
  }, [countdown]);

  const accountPlaceholder = useMemo(() => {
    return verifyType === 'phone' ? t('login.phonePlaceholder') : t('login.emailPlaceholder');
  }, [verifyType, t]);

  const handlePasswordLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLocalError(null);
    clearError();
    if (!username || !password) {
      setLocalError(t('login.required')); return;
    }
    try {
      await login({ username, password });
      navigate('/');
    } catch (err: any) {
      // 错误由context统一处理
      console.error('密码登录失败:', err);
    }
  };

  const sendVerifyCode = async () => {
    setLocalError(null);
    clearError();
    // 基础校验
    if (!account) { setLocalError(t('login.accountRequired')); return; }
    if (verifyType === 'phone' && !/^\d{6,15}$/.test(account)) { setLocalError(t('login.invalidPhone')); return; }
    if (verifyType === 'email' && !/.+@.+\..+/.test(account)) { setLocalError(t('login.invalidEmail')); return; }

    try {
      const res = await sendCode(account, verifyType);
      if ((res as any).success === false) {
        setLocalError((res as any).message || t('login.sendFailed'));
        return;
      }
      setCountdown((res as any).data?.expireIn || 60);
    } catch (err: any) {
      setLocalError(err?.response?.data?.message || t('login.sendFailed'));
    }
  };

  const handleCodeLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLocalError(null);
    clearError();
    if (!account) { setLocalError(t('login.accountRequired')); return; }
    if (!code) { setLocalError(t('login.codeRequired')); return; }

    try {
      await loginByCode({ account, code, type: verifyType });
      navigate('/');
    } catch (err: any) {
      console.error('验证码登录失败:', err);
      setLocalError(err?.response?.data?.message || err?.message || t('login.loginFailed'));
    }
  };

  return (
    <div className="login">
      <h2>{t('login.title')}</h2>

      {/* 登录方式切换 */}
      <div className="form-group" style={{ display: 'flex', gap: '8px', marginBottom: '1rem' }}>
        <button
          type="button"
          className="btn"
          style={{ backgroundColor: mode === 'password' ? '#4fa8c7' : undefined }}
          onClick={() => { setMode('password'); setLocalError(null); clearError(); }}
        >
          {t('login.passwordLogin')}
        </button>
        <button
          type="button"
          className="btn"
          style={{ backgroundColor: mode === 'code' ? '#4fa8c7' : undefined }}
          onClick={() => { setMode('code'); setLocalError(null); clearError(); }}
        >
          {t('login.codeLogin')}
        </button>
      </div>

      {/* 错误展示 */}
      {(localError) && (
        <div style={{ color: '#d93025', marginBottom: '1rem' }}>{localError}</div>
      )}

      {mode === 'password' ? (
        <form onSubmit={handlePasswordLogin}>
          <div className="form-group">
            <label htmlFor="username">{t('login.username')}</label>
            <input
              type="text"
              id="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              required
            />
          </div>
          <div className="form-group">
            <label htmlFor="password">{t('login.password')}</label>
            <input
              type="password"
              id="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
          </div>
          <button type="submit" disabled={loading}>{t('login.loginButton')}</button>
        </form>
      ) : (
        <form onSubmit={handleCodeLogin}>
          <div className="form-group" style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
            <label>{t('login.loginBy')}</label>
            <label style={{  alignItems: 'right', gap: '12px',  width: '100px' }}>
              <input type="radio" checked={verifyType === 'phone'} onChange={() => setVerifyType('phone')} />
              {t('login.phone')}
            </label>
            <label style={{ alignItems: 'right', gap: '12px',  width: '100px' }}>
              <input type="radio" checked={verifyType === 'email'} onChange={() => setVerifyType('email')} />
              {t('login.email')}
            </label>
          </div>

          <div className="form-group">
            <label htmlFor="account">{t('login.account')}</label>
            <input
              type="text"
              id="account"
              placeholder={accountPlaceholder}
              value={account}
              onChange={(e) => setAccount(e.target.value)}
              required
            />
          </div>

          <div className="form-group" style={{ display: 'flex', gap: '8px' }}>
            <div style={{ flex: 1 }}>
              <label htmlFor="code">{t('login.verifyCode')}</label>
              <input
                type="text"
                id="code"
                value={code}
                onChange={(e) => setCode(e.target.value)}
                required
              />
            </div>
            <div style={{ display: 'flex', alignItems: 'flex-end' }}>
              <button type="button" className="btn" onClick={sendVerifyCode} disabled={countdown > 0 || loading}>
                {countdown > 0 ? t('login.resendIn', { seconds: countdown }) : t('login.sendCode')}
              </button>
            </div>
          </div>

          <button type="submit" disabled={loading}>{t('login.loginButton')}</button>
        </form>
      )}
    </div>
  );
};

export default Login;